/*
 * @Author: fhw
 * @Date: 2022-07-01 15:39:20
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-01-31 16:26:02
 * @Description:
 */
import { defineComponent, PropType, ref } from 'vue'
import { CloudUploadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { isNil } from 'ramda'
import { errorTips } from '@/utils'
export interface FileInfo {
	file: Blob
	fileList: FileItem[]
}
export interface OssData {
	filename: string
	url: string
}
interface FileItem {
	uid: string
	name?: string
	status?: string
	response?: string
	url?: string
	type?: string
	size: number
	originFileObj: any
}
const props = {
	accept: {
		type: String as PropType<string>,
		default: '.jpg,.png,.jpeg',
	},
	reg: {
		type: String as PropType<string>,
		default: '.(jpg|png|jpeg)$',
	},
} as const
export default defineComponent({
	emits: ['change'],
	props,
	setup(props, { emit, slots }) {
		const loading = ref(false)
		async function handleChange(info: FileInfo) {
			if (!new RegExp(props.reg).test((info.file as any).name.toLowerCase())) {
				message.error(`上传格式不正确，请上传${props.accept}格式`)
				return false
			}
			loading.value = true
			const curFiles = info.file
			const formData = new FormData()
			if (isNil(curFiles)) return
			formData.append('file', curFiles)
			const { success, data } = await API.blog.upload.uploadOSS.request({ data: formData })
			loading.value = false
			success ? emit('change', data) : errorTips('上传文件失败')
		}
		return () => (
			<a-upload
				name="avatar"
				list-type="picture-card"
				class="avatar-uploader"
				show-upload-list={false}
				before-upload={() => false}
				onChange={handleChange}
				accept={props.accept}
			>
				{slots['text'] ? (
					slots['text']?.()
				) : (
					<p class="ant-upload-drag-icon">
						<CloudUploadOutlined style="font-size: 40px;color:#40a9ff" />
					</p>
				)}
			</a-upload>
		)
	},
})
